package com.suneee.cloud.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.suneee.base.sendmsg.SendSmsFactory;
import com.suneee.base.sendmsg.bean.SendMsgBean;
import com.suneee.base.sendmsg.bean.SendType;
import com.suneee.base.util.ContextHelper;
import com.suneee.base.util.EmailUrlUtil;
import com.suneee.base.util.MD5Utils;
import com.suneee.cloud.admin.dao.AdministratorDao;
import com.suneee.cloud.admin.entity.AdministratorBean;
import com.suneee.cloud.admin.resources.AdminError;
import com.suneee.cloud.admin.service.AdministratorService;
import com.suneee.context.page.Page;
import com.suneee.core.error.Assert;
import com.suneee.core.error.ErrorUtils;
import com.suneee.core.util.DateUtils;
import com.suneee.core.util.StringUtils;
import com.suneee.enterprise.dao.EnterpriseDao;
import com.suneee.enterprise.entity.Enterprise;
import com.suneee.role.dao.RoleDao;
import com.suneee.role.entity.Role;
import com.suneee.role.service.RoleService;
import com.suneee.sso.admin.entity.Administrator;

@Service("api-administrator")
public class AdministratorServiceImpl implements AdministratorService {

	@Autowired
	private AdministratorDao administratorDao;

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private EnterpriseDao enterpriseDao;
	
	private String mailSubject;
	
	private String mailContent;

	private String mailUrl;
	
	private String mobileSubject;
	
	@Override
	@Transactional
 	public void updPwd(String adminId, String password, String newPassword) {
		Assert.notEmpty(adminId, "adminId");
		Assert.notEmpty(password, "password");
		Assert.notEmpty(newPassword, "newPassword");
		
	    Administrator admin = administratorDao.select(Integer.valueOf(adminId));
		if (!MD5Utils.md5(password.trim()).equals(admin.getPassword())) {
			throw ErrorUtils.wrap(AdminError.OLD_PASSWORD_MISMATCH);
		}
		if (newPassword.trim().equals(password.trim())) {
			throw ErrorUtils.wrap(AdminError.NEW_EQUALS_OLD);
		}
		 
		administratorDao.updPassword(adminId, MD5Utils.md5(newPassword.trim())); 
		
	}
	
	@Override
	public void updPwdEn(String adminId, String identity, String password,String newPassword, String commitNewPwd) {
		Assert.notEmpty(adminId, "adminId");
		Assert.notEmpty(identity, "identity");
		Assert.notEmpty(password, "password");
		Assert.notEmpty(newPassword, "newPassword");
		Assert.notEmpty(commitNewPwd, "commitNewPwd");
		
		String adminIdStr  = EmailUrlUtil.decrypt(adminId);
		String identityStr = EmailUrlUtil.decrypt(identity);
		String redisIdeStr = ContextHelper.getIdentityStr(adminIdStr);
		
		if(redisIdeStr == null){
			throw ErrorUtils.wrap(AdminError.UPDATE_PASSWORD_EXCEPTION);
		}
		
		if(!identityStr.equals(redisIdeStr)){
			throw ErrorUtils.wrap(AdminError.UPDATE_PASSWORD_EXCEPTION);
		}
		
		Administrator admin = administratorDao.select(Integer.valueOf(adminIdStr));
		if (!MD5Utils.md5(password.trim()).equals(admin.getPassword())) {
			throw ErrorUtils.wrap(AdminError.OLD_PASSWORD_MISMATCH);
		}
		if (newPassword.trim().equals(password.trim())) {
			throw ErrorUtils.wrap(AdminError.NEW_EQUALS_OLD);
		}
		if (!newPassword.trim().equals(commitNewPwd)) {
			throw ErrorUtils.wrap(AdminError.TWOPASSWORD_INPUT_NOT_CONSISTENT);
		}
		
		//删除redis标识
		ContextHelper.delteIdentityStr(adminId);
		
		admin.setLastUpdateTime(DateUtils.getCurrentTimestamp());
		admin.setEnabled("1");
		admin.setPassword(MD5Utils.md5(newPassword.trim()));
		administratorDao.update(admin);
	}
	
	@Override
	public Page<Map<String,Object>> list(AdministratorBean bean) {
		if(bean == null)
			bean = new AdministratorBean();
		if(!bean.isAdmin())
			bean.setEnterpriseCode("suneee");
		 Page<Map<String,Object>> list = administratorDao.list(bean);
		 if(list != null){
			 for (int i = 0; i < list.getItems().size(); i++) {
/*				 Administrator admin = list.getItems().get(i);
				 Administrator adminUser = administratorDao.select(Integer.parseInt(admin.getCreatePerson()));
				 if(adminUser != null)
					 admin.setCreatePersionName(adminUser.getName());*/
				 list.getItems().get(i).put("createPersionName", list.getItems().get(i).get("name").toString());
			}
		 }
		 return list;
	}
	
	@Override
	public Page<Map<String,Object>> listEn(AdministratorBean bean) {
		if(bean == null)
			bean = new AdministratorBean();
		bean.setEnterpriseCode(ContextHelper.getCurrentLoginInfo().getEnterpriseCode());
//		if(!StringUtils.isEmpty(bean.getEnabled())){
//			 if("true".equals(bean.getEnabled())){
//				 bean.setEnabled("1");
//			 }else{
//				 bean.setEnabled("0");
//			 }
//		}
		Page<Map<String,Object>> list = administratorDao.list(bean);
		 if(list != null){
			 for (int i = 0; i < list.getItems().size(); i++) {
//				 Administrator admin = list.getItems().get(i);
//				 Administrator adminUser = administratorDao.select(Integer.parseInt(admin.getCreatePerson()));
//				 if(adminUser != null)
				 list.getItems().get(i).put("createPersionName", list.getItems().get(i).get("name").toString());
			}
		 }
		 return list;
	}

	@Override
	public Administrator getAdministrator(String adminId) {
		Assert.notEmpty(adminId, "adminId");
		
		Administrator admin = administratorDao.select(Integer.valueOf(adminId));
		if(null != admin && !StringUtils.isEmpty(admin.getEnterpriseCode()))
		{
			List<Enterprise> etList = enterpriseDao.selectWhere(" enterprise_code = ?", admin.getEnterpriseCode());
			if(null != etList && etList.size() > 0)
			{
				admin.setEnterpriseName(etList.get(0).getName());
				admin.setEnterprise(etList.get(0));
			}
		}
		//获取拥有的权限
		if(admin != null){
			List<Role> roleList = roleService.adminRoleList(admin.getAdminId(),ContextHelper.getCurrentLoginInfo().getPlatformFlag());
			List<Integer> roleIdList = null;
			if(roleList != null){
				roleIdList = new ArrayList<>();
				for(Role role : roleList){
					roleIdList.add(role.getRoleId());
				}
			}
			admin.setRoleList(roleList);
			admin.setRoleIdList(roleIdList);
			if(!StringUtils.isEmpty(admin.getDeptCode()))
			{
				String depCode = admin.getDeptCode();
				List<String> dept = new ArrayList<String>();
				int i= 0;
				while(true)
				{
					i = i+2;
					dept.add(depCode.substring(0, i));
					if(i >= depCode.length())
					{
						break;
					}
				}
				admin.setDeptList(dept.toArray());
			}
		}
		
		
		return admin;
	}

	@Override
	@Transactional
	public void updateAdmin(AdministratorBean adminBean) {
		 Assert.notEmpty(String.valueOf(adminBean.getAdminId()), "adminId");
		 
		 
		 Administrator oldAdmin = administratorDao.select(Integer.valueOf(adminBean.getAdminId()));
		 
		 if(!StringUtils.isEmpty(adminBean.getAccount()))
			 oldAdmin.setAccount(adminBean.getAccount());
		 if(!StringUtils.isEmpty(adminBean.getName()))
			 oldAdmin.setName(adminBean.getName());
		 if(!StringUtils.isEmpty(adminBean.getNick()))
			 oldAdmin.setNick(adminBean.getNick());
		 if(!StringUtils.isEmpty(adminBean.getEmail()))
			 oldAdmin.setEmail(adminBean.getEmail());
		 if(!StringUtils.isEmpty(adminBean.getMobile()))
			 oldAdmin.setMobile(adminBean.getMobile());
		 if(!StringUtils.isEmpty(adminBean.getAddress()))
			 oldAdmin.setAddress(adminBean.getAddress());
		 if(!StringUtils.isEmpty(adminBean.getSignature()))
			 oldAdmin.setSignature(adminBean.getSignature());
		 if(!StringUtils.isEmpty(adminBean.getEnabled())) 
			 oldAdmin.setEnabled(adminBean.getEnabled());
		 oldAdmin.setDeptCode(adminBean.getDeptCode());
		 oldAdmin.setPhoto(adminBean.getPhoto());
		 oldAdmin.setSex(adminBean.isSex());
		 
		 administratorDao.update(oldAdmin);
		 
		 //产品经理确定，平台端企业账号不修改角色信息
		 //删除原有角色关联信息
		 if(adminBean.isAdmin()){
			 if(adminBean.getRoleIdList() != null && !adminBean.getRoleIdList().isEmpty()){
				 roleDao.deleteAdminRoleByAdmin(oldAdmin.getAdminId());
			 }
			 //授予角色
			 if(adminBean.getRoleIdList() != null && !adminBean.getRoleIdList().isEmpty()){
				roleService.addAdminRole(oldAdmin.getAdminId(), adminBean.getRoleIdList());
			 }
		 }
	}

	@Override
	@Transactional
	public void addAdmin(Administrator admin) {
		
		Assert.notEmpty(admin.getAccount(), "账号");
        Assert.notEmpty(admin.getPassword(), "密码");
        //Assert.notEmpty(admin.getEnterpriseCode(), "企业编码");
        //Assert.notEmpty(admin.getRoleList(), "角色列表");
        
        
        Administrator loginAdmin = ContextHelper.getCurrentLoginInfo();
		
        boolean isExist = administratorDao.existsAccountAdmin(admin.getAccount());
		//判断当前是否已经存在平台管理员账号
        if(isExist){
        	throw ErrorUtils.wrap(AdminError.ACCOUNT_IN_USE);
        }
		
		if (admin.getPassword().length() != 32) {
			admin.setPassword(MD5Utils.md5(admin.getPassword()));
        }
		
		admin.setEnterpriseCode(Administrator.CODE);
		//admin.setAdmin(true);//是管理员
		admin.setCreatePerson(loginAdmin.getAdminId().toString());
		admin.setRegisterTime(DateUtils.getCurrentTimestamp());
		admin.setLastUpdateTime(admin.getRegisterTime());
		 
		//插入对象到数据库
		administratorDao.insert(admin);
		
		//授予角色
		if(admin.getRoleIdList() != null && !admin.getRoleIdList().isEmpty()){
			roleService.addAdminRole(admin.getAdminId(), admin.getRoleIdList());
		}
	}
	
	@Override
	@Transactional
	public void addEnAdmin(Administrator admin) {
		Assert.notEmpty(admin.getEmail(), "邮箱");
        Assert.notEmpty(admin.getEnterpriseCode(), "企业编码");
        
        Administrator loginAdmin = ContextHelper.getCurrentLoginInfo();
		
        //判断是否已经存在当前企业的管理员账号
        if(checkAdminByEnCode(admin.getEnterpriseCode())){
        	throw ErrorUtils.wrap(AdminError.ENTERPRISE_ADMINACCOUNT_EXIT);
        }
        admin.setAccount(admin.getEmail());
        admin.setPassword(MD5Utils.md5("suneee123456"));//默认密码
        
        admin.setAdmin(true);//是管理员
		admin.setCreatePerson(loginAdmin.getAdminId().toString());
		admin.setRegisterTime(DateUtils.getCurrentTimestamp());
		admin.setLastUpdateTime(admin.getRegisterTime());
        
		//插入企业管理员对象信息
		administratorDao.insert(admin);
		
		//查询默认的企业管理员角色权限信息
		List<Role> roleList = roleService.publicRoles();
		List<Integer> roleIdList = new ArrayList<Integer>();
		for (Role role : roleList) {
			roleIdList.add(role.getRoleId());
		}
		//授予默认角色
		if(!roleIdList.isEmpty()){
			roleService.addAdminRole(admin.getAdminId(), roleIdList);
		}
		SendMsgBean msgBean = null;
		SendSmsFactory smsFactory = new SendSmsFactory();
		//账号创建成功后，发送激活邮件，以及发送短信提醒用户去邮箱激活
		//发送激活邮件
		if(!StringUtils.isEmpty(admin.getEmail())){
			String adminId  = EmailUrlUtil.encrypt(admin.getAdminId().toString());
			String UUID = StringUtils.getUUID();
			admin.setIdentityStr(UUID);
			ContextHelper.setIdentityStr(admin);//放入redis缓存
			String identityStr = EmailUrlUtil.encrypt(UUID);
			String url = "<a href='"+mailUrl+"/"+adminId+"/"+identityStr+"'>"+mailUrl+"/"+adminId+"/"+identityStr+"</a>";
			boolean emailflag = false;
			msgBean = new SendMsgBean();
			msgBean.setRecievePerson(admin.getEmail());
			msgBean.setSubject(mailSubject);
			msgBean.setContent(mailContent +"："+ url);
			msgBean.setSendType(SendType.SEND_EMAIL);
			emailflag = smsFactory.getSendServiceInstance(msgBean).sendMsg(msgBean);
			if (!emailflag) {
				throw ErrorUtils.wrap(AdminError.USER_EMAIL_SEND_ERROR);
			}
		}
		//发送提示短信
		if(!StringUtils.isEmpty(admin.getMobile())){
			boolean mobileflag = false;
			msgBean = new SendMsgBean();
		    msgBean.setRecievePerson(admin.getMobile());
		    msgBean.setContent(mobileSubject);
		    msgBean.setSendType(SendType.SEND_SMS);
		    
		    mobileflag = smsFactory.getSendServiceInstance(msgBean).sendMsg(msgBean);
		    if (!mobileflag) {
				throw ErrorUtils.wrap(AdminError.USER_MOBILE_SEND_ERROR);
			}
		}
		
	}
	
	@Override
	@Transactional
	public void addAccount(Administrator admin) {
		Assert.notEmpty(admin.getAccount(), "账号");
        Assert.notEmpty(admin.getPassword(), "密码");
//        Assert.notEmpty(admin.getEnterpriseCode(), "企业编码");
        Assert.notEmpty(admin.getRoleIdList(), "角色列表");
        Assert.notEmpty(admin.getDeptCode(), "账号组");
        
        
        Administrator loginAdmin = ContextHelper.getCurrentLoginInfo();
        admin.setEnterpriseCode(loginAdmin.getEnterpriseCode());
        
        
		//判断当前企业下是否存在此账号
        boolean isExist = existsAccount(admin.getEnterpriseCode(), admin.getAccount());
		if(isExist){
			throw ErrorUtils.wrap(AdminError.ACCOUNT_IN_USE);
		}
		
		if (admin.getPassword().length() != 32) {
			admin.setPassword(MD5Utils.md5(admin.getPassword()));
        }
		
		admin.setCreatePerson(loginAdmin.getAdminId().toString());
		admin.setRegisterTime(DateUtils.getCurrentTimestamp());
		admin.setLastUpdateTime(admin.getRegisterTime());
		
		//插入对象到数据库
		administratorDao.insert(admin);
		
		//授予角色
		if(admin.getRoleIdList() != null && !admin.getRoleIdList().isEmpty()){
			roleService.addAdminRole(admin.getAdminId(), admin.getRoleIdList());
		}
		
	}

	@Override
	@Transactional
	public void deleteAdmin(List<Integer> adminIds) {
		Assert.notNull(adminIds, "管理员编号");
		try{
            administratorDao.delete(adminIds);
        	roleDao.deleteAdminRoleByAdmin(adminIds.get(0));
        }catch(Exception e){
            throw ErrorUtils.wrap(AdminError.DETELE_ERROR);
        }
	}
	
	@Override
	public boolean checkAdminByEnCode(String enterpriseCode) {
		Assert.notNull(enterpriseCode, "企业编码");
		return administratorDao.existsAdmin(enterpriseCode);
	}

	//验证是否存在某个企业下的账号
	public  boolean existsAccount(String enterpriseCode, String account){
		return administratorDao.existsAccount(enterpriseCode, account);
	}

	@Override
	public void resetPassword(String adminId) {
		Assert.notEmpty(String.valueOf(adminId), "adminId");
		
		Administrator oldAdmin = administratorDao.select(Integer.valueOf(adminId));
		
		oldAdmin.setPassword(MD5Utils.md5("suneee123456"));
		
		administratorDao.update(oldAdmin);
	}

	public String getMailSubject() {
		return mailSubject;
	}

	public void setMailSubject(String mailSubject) {
		this.mailSubject = mailSubject;
	}

	public String getMailContent() {
		return mailContent;
	}

	public void setMailContent(String mailContent) {
		this.mailContent = mailContent;
	}
	public String getMailUrl() {
		return mailUrl;
	}
	public void setMailUrl(String mailUrl) {
		this.mailUrl = mailUrl;
	}
	public String getMobileSubject() {
		return mobileSubject;
	}
	public void setMobileSubject(String mobileSubject) {
		this.mobileSubject = mobileSubject;
	}
	
	@Override
	public void deleteAccount(String enterpriseCode) {
		administratorDao.deleteAccount(enterpriseCode);
	}

	
	@Override
	public void resetPasswordEn(String adminId) {
		Assert.notEmpty(String.valueOf(adminId), "adminId");
		
		Administrator oldAdmin = administratorDao.select(Integer.valueOf(adminId));
		
		oldAdmin.setPassword(MD5Utils.md5("123456"));
		
		administratorDao.update(oldAdmin);
	}

}
